/*
 * @Author: Wangjun
 * @Date: 2021-06-04 22:33:21
 * @LastEditTime: 2021-08-11 15:35:32
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \lua\luaquery\query.go
 * hnxr
 */
package luaquery

import (
	"gitee.com/haodreams/query"
	lua "github.com/yuin/gopher-lua"
)

const luaQuery = "query"

func newQuery(l *lua.LState) int {
	n := l.GetTop()
	if n < 1 {
		l.Push(lua.LString("Paramster error"))
		return 1
	}
	tableName := l.CheckString(1)
	table := query.GetQuery(tableName)
	ud := l.NewUserData()
	ud.Value = table
	l.SetMetatable(ud, l.GetTypeMetatable(luaQuery))
	l.Push(ud)
	return 1
}

func checkQuery(l *lua.LState) *query.Query {
	ud := l.CheckUserData(1)
	if v, ok := ud.Value.(*query.Query); ok {
		return v
	}
	l.ArgError(1, "check query expected")
	return nil
}

func pushQuery(l *lua.LState, q *query.Query) {
	ud := l.NewUserData()
	ud.Value = q
	l.SetMetatable(ud, l.GetTypeMetatable(luaQuery))
	l.Push(ud)
}

//lua 值转为 go值
func lvalue2interface(val lua.LValue) interface{} {
	switch val.Type() {
	case lua.LTBool:
		if lv, ok := val.(lua.LBool); ok {
			return bool(lv)
		}
	case lua.LTNumber:
		if lv, ok := val.(lua.LNumber); ok {
			return float64(lv)
		}
	case lua.LTString:
		if lv, ok := val.(lua.LString); ok {
			return string(lv)
		}
	}
	return nil
}

//等于
func eq(l *lua.LState) int {
	q := checkQuery(l)
	key := l.CheckString(2)
	val := l.Get(3)
	v := lvalue2interface(val)
	q.EQ(key, v, true)
	pushQuery(l, q)
	return 1
}

//取平均值
func avg(l *lua.LState) int {
	q := checkQuery(l)
	key := l.CheckString(2)
	val, err := q.Avg(key)
	l.Push(lua.LNumber(val.(float64)))
	if err != nil {
		l.Push(lua.LString(err.Error()))
		return 2
	}
	return 1
}

//求和
func sum(l *lua.LState) int {
	q := checkQuery(l)
	key := l.CheckString(2)
	val, err := q.Avg(key)
	l.Push(lua.LNumber(val.(float64)))
	if err != nil {
		l.Push(lua.LString(err.Error()))
		return 2
	}
	return 1
}

//最小值
func min(l *lua.LState) int {
	return 1
}

//最大值
func max(l *lua.LState) int {
	return 1
}
